<template>
  <div class="qr-code">
    <QrcodeVue
        :value="value"
        :size="size"
        :level="type"
        :background="colorLight"
        :foreground="colorDark"
        :margin="margin"
        :version="version"
        @render="handleGenerated"
        @renderError="handleError"
    />
    <span class="sr-only">QR Code: {{ value }}</span>
  </div>
</template>

<script setup>
import {onMounted} from 'vue'
import QrcodeVue from 'qrcode.vue'

const props = defineProps({
  value: {
    type: String,
    required: true
  },
  type: {
    type: String,
    default: 'H',
    validator(value) {
      return ['L', 'M', 'Q', 'H'].includes(value.toUpperCase())
    }
  },
  size: {
    type: Number,
    default: 200
  },
  colorDark: {
    type: String,
    default: '#000000'
  },
  colorLight: {
    type: String,
    default: '#ffffff'
  },
  margin: {
    type: Number,
    default: 4
  },
  version: {
    type: Number,
    default: undefined
  }
})

const emit = defineEmits(['generated', 'error'])

const handleGenerated = (dataUrl) => {
  emit('generated', dataUrl)
}

const handleError = (error) => {
  emit('error', error)
}

onMounted(() => {
  if (!props.value) {
    emit('error', new Error('QR code value is required'))
  }
})
</script>

<style scoped>
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  border: 0;
}

.qr-code {
  display: inline-block;
  line-height: 0;
}
</style>